package com.angel.libreoffice;

import java.io.File;

import com.sun.star.beans.PropertyValue;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;

import ooo.connector.BootstrapSocketConnector;

public class Word2Pdf {
	// libreoffice的指令目录
	static String oooExeFolder = "E:\\Program Files\\LibreOffice 5\\program\\";
	
	public static void main(String[] args) throws Exception {
		String source = "c:/java-123.doc";
		String destination = "c:/java-123.pdf";
		
		  source = "c:/ly.doc";
		  destination = "c:/ly.pdf";
		
		word2pdf(source,destination);

	}

	public static void word2pdf(String source, String destination) throws Exception {

		XComponentContext xContext = BootstrapSocketConnector.bootstrap(oooExeFolder);
		XMultiComponentFactory xMCF = xContext.getServiceManager();
		Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
		XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, oDesktop);

		// Load the Document 
//		String workingDir = "C:/";
//		String myTemplate = "java-123.doc";

//		if (!new File(workingDir + myTemplate).canRead()) {
//			throw new RuntimeException("Cannot load template:" + new File(workingDir + myTemplate));
//		}
		
		if (!new File(source).canRead()) {
			throw new RuntimeException("Cannot load template:" + new File(source));
		}

		XComponentLoader xCompLoader = (XComponentLoader) UnoRuntime
				.queryInterface(com.sun.star.frame.XComponentLoader.class, xDesktop);

//		String sUrl = "file:///" + workingDir + myTemplate;

		String sUrl = "file:///" +source;

		PropertyValue[] propertyValues = new PropertyValue[0];

		propertyValues = new PropertyValue[1];
		propertyValues[0] = new PropertyValue();
		propertyValues[0].Name = "Hidden";
		propertyValues[0].Value = new Boolean(true);
		
		XComponent xComp = xCompLoader.loadComponentFromURL(sUrl, "_blank", 0, propertyValues);

		// save as a PDF
		XStorable xStorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, xComp);

		propertyValues = new PropertyValue[2];
		propertyValues[0] = new PropertyValue();
		propertyValues[0].Name = "Overwrite";
		propertyValues[0].Value = new Boolean(true);
		propertyValues[1] = new PropertyValue();
		propertyValues[1].Name = "FilterName";
		propertyValues[1].Value = "writer_pdf_Export";
		
		// Appending the favoured extension to the origin document name
//		String myResult = "C:/" + "letterOutput.pdf";
		String myResult = destination;
		xStorable.storeToURL("file:///" + myResult, propertyValues);
		
		System.out.println("Saved " + myResult);

		// shutdown
		xDesktop.terminate();

	}
}